//
//  HMComposeController.swift
//  XinLangWeibo10
//
//  Created by 白利兵 on 15/10/28.
//  Copyright © 2015年 itheima. All rights reserved.
//
// 1.懒加载控件
// 2.构造函数
// 3.设置UI
// 4.模型属性
// 5.准备数据
import UIKit
import SVProgressHUD
class HMComposeController: UIViewController {
    var emoiconString: String = ""
    // MARK: -视图生命周期
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        // 设置UI
        setupUI()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // 监听键盘改变的通知（系统通知）
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 激活键盘 - 如果已经存在照片控制器视图，不再激活键盘
        if picturePickerController.view.frame.height == 0 {
            textView.becomeFirstResponder()
        }
    }
    // MARK: 注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    // MARK: -懒加载控件
    private lazy var statusLabel: UILabel = UILabel(title: "发微博", fontSize: 15, color: UIColor.darkGrayColor())
    private lazy var nameLabel: UILabel = UILabel(title: UserAccountViewModel.shareUserAccount.account?.screen_name ?? "新浪微博", fontSize: 13, color: UIColor.grayColor())
    // 工具条
    private lazy var toolBar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 44))
    // 占位label
    private lazy var placeHolderLabel: UILabel = UILabel(title: "分享新鲜事...", fontSize: 17, color: UIColor.darkGrayColor())
    // textView
    private lazy var textView: UITextView = {
        let textview = UITextView()
        textview.font = UIFont.systemFontOfSize(18)
        // 允许垂直拉拽
        textview.alwaysBounceVertical = true
        // 拉拽时隐藏键盘
        textview.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        // 设置代理
        textview.delegate = self
        return textview
        }()

    // 表情键盘(weak self防止循环引用)
    private lazy var emoticonKey: EmoticonView = EmoticonView  { [weak self](emoticon) -> () in
        self!.textView.insertEmoticon(emoticon)
    }
    // 图片选择控制器
    private lazy var picturePickerController = PicturePickerController()
    // MARK: 事件监听
    // 监听键盘改变
    @objc private func keyboardWillChange(notify: NSNotification) {
        //print(notify)
        textView.font = UIFont.systemFontOfSize(18)
        // 更新toolbar的约束
        // 1. 获取目标的rect（是一个字典）
        let rect = (notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        // 2. 计算偏移量
        let offset = rect.origin.y - UIScreen.mainScreen().bounds.height
        
        // 3. 获取动画时长
        let duration = (notify.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        // 4. 获取动画曲线值
        let curve = (notify.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        // 5. 更新约束
        if picturePickerController.view.bounds.height == 400 {
            picturePickerController.view.snp_updateConstraints(closure: { (make) -> Void in
                make.height.equalTo((view.bounds.height + offset)*0.4)
            })
        }
        self.toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        // 6. 动画改变约束
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    // 监听取消按钮，做控制器跳转
    @objc private func cancelBtnClick() {
        // 取消第一响应者
        textView.resignFirstResponder()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    //监听发送按钮点击
    @objc private func sendStatus() {
        // 获取图片数据
        let image = picturePickerController.pictures.last
        print("发送")
        NetworkTools.sharedTools.sendStatus(textView.emoticonText, image: image) { (result, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络加载错误")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发布成功")
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    }
}
// MARK: - UITextView代理
extension HMComposeController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        // 隐藏placeHolderLabel
        placeHolderLabel.hidden = textView.hasText()
        // 根据是否有文字来使能发送按钮
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
// MARK: 设置UI
extension HMComposeController {
    private func setupUI() {
        // 0. 取消自动调整滚动视图间距
        automaticallyAdjustsScrollViewInsets = false
        // 准备navigtionBar
        prepareNavigationBar()
        // 准备Toolbar
        prepareToolBar()
        // 准备textView
        prepareTextView()
        // 准备PictureController
        preparePictureController()
    }
}
// MARK: - 准备PictureController
extension HMComposeController {
    private func preparePictureController() {
        // 0. 添加子控制器
        addChildViewController(picturePickerController)
        picturePickerController.view.backgroundColor = UIColor.orangeColor()
        // 1. 添加视图
        view.insertSubview(picturePickerController.view, belowSubview: toolBar)
        
        // 2. 自动布局
        picturePickerController.view.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(toolBar.snp_top)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(0)
        }
    }
}
// MARK: 准备textView
extension HMComposeController {
    
    private func prepareTextView() {
        view.addSubview(textView)
        textView.addSubview(placeHolderLabel)
        
        // textView
        textView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.bottom.equalTo(toolBar.snp_top)
        }
        // placeholder
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(textView.snp_left).offset(6)
            make.top.equalTo(textView.snp_top).offset(8)
        }
        //textView.becomeFirstResponder()
    }
}
// MARK: - 准备toolBar
extension HMComposeController {
    private func prepareToolBar() {
        // 设置toolbar
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        let itemName = ["compose_toolbar_picture", "compose_mentionbutton_background", "compose_trendbutton_background", "compose_emoticonbutton_background", "compose_addbutton_background"]
        let selItemName = ["compose_toolbar_picture_highlighted", "compose_mentionbutton_background_highlighted", "compose_trendbutton_background_highlighted", "compose_emoticonbutton_background_highlighted", "compose_addbutton_background_highlighted"]
        var items = [UIBarButtonItem]()
        // 定义索引
        var index = 0
        // 循环添加toolbar子控件
        for name in itemName {
            let button = UIButton()
            button.setImage(UIImage(named: name), forState: UIControlState.Normal)
            button.setImage(UIImage(named: selItemName[index++]), forState: UIControlState.Highlighted)
            button.tag = index
            button.addTarget(self, action: "itemClick:", forControlEvents: UIControlEvents.TouchUpInside)
            button.sizeToFit()
            let item = UIBarButtonItem(customView: button)
            items.append(item)
            let FlexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
            // 如果是最后一个item则不再添加弹簧
            if index != itemName.count {
                items.append(FlexibleSpace)
            }
            toolBar.items = items
        }
        view.addSubview(toolBar)
        // toolBar布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }
    }
    @objc private func itemClick(sender: UIButton) {
        switch sender.tag {
        case 1:
            print("添加图片")
            // 判断是否弹出页面
            if picturePickerController.view.bounds.height > 0 {
                return
            }
            // textView解除第一响应者
            textView.resignFirstResponder()
            // 创建一个图片选择控制器
            picturePickerController.view.snp_updateConstraints(closure: { (make) -> Void in
                make.height.equalTo(400)
            })
            // 更新textView的布局
            textView.snp_remakeConstraints(closure: { (make) -> Void in
                make.top.equalTo(snp_topLayoutGuideBottom)
                make.left.equalTo(view.snp_left)
                make.right.equalTo(view.snp_right)
                make.bottom.equalTo(picturePickerController.view.snp_top)
            })
            // 更新约束
            view.layoutIfNeeded()
            
            break
        case 2:
            print("@好友")
            break
        case 3:
            print("添加话题")
            break
        case 4:
            print("添加表情")
            // 选择键盘
            selectKeyBoard()
            break
        case 5:
            print("添加长微博")
            break
        default:
            break
        }
    }
    @objc private func Back() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}
// MARK: - 选择键盘
extension HMComposeController {
    // 选择键盘
    private func selectKeyBoard() {
        // 接触第一响应者
        textView.resignFirstResponder()
        // 设置输入视图
        textView.inputView = (textView.inputView == nil ? emoticonKey : nil)
        // 更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            let height = textView.inputView == nil ? 258 : emoticonKey.bounds.height
            make.bottom.equalTo(view.snp_bottom).offset(-height)
        }
        // 重新开启第一响应者
        textView.becomeFirstResponder()
    }
}
// MARK: - 准备navigtionBar
extension HMComposeController {
    private func prepareNavigationBar() {
        // 设置取消按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelBtnClick")
        // 设置发送按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        // 禁用发送按钮
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 设置titleView
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        navigationItem.titleView = titleView
        
        // 添加控件
        titleView.addSubview(statusLabel)
        titleView.addSubview(nameLabel)
        
        // 设置布局
        // statusLabel
        statusLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        // nameLabel
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
    }
}




